package com.zzyy.study;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @auther zzyy
 * @create 2024-07-06 18:01
 */
public class DelayQueueDemo
{
    public static void main(String[] args) throws InterruptedException
    {
        BlockingQueue<Employee> blockingQueue = new DelayQueue<>();

        blockingQueue.put(new Employee("z3","doJava",2,TimeUnit.SECONDS));
        blockingQueue.put(new Employee("li4","doMysql",4,TimeUnit.SECONDS));
        blockingQueue.put(new Employee("w5","doFlink",1,TimeUnit.SECONDS));

        while(!blockingQueue.isEmpty())
        {
            System.out.println(blockingQueue.take());
        }
    }
}

@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
class Employee implements Delayed
{
    private String name;
    private String task;
    private long   start = System.currentTimeMillis();
    private long   delay;//延时多少时间单位后触发，弹出队列   action = start + delay

    public Employee(String name, String task, long delay,TimeUnit timeUnit)
    {
        this.name = name;
        this.task = task;
        this.delay = TimeUnit.MILLISECONDS.convert(delay,timeUnit);
    }

    @Override
    public long getDelay(TimeUnit timeUnit)
    {
        //零值或负值表示延迟已经过去,actionTime = currentTime + delayTime
        return timeUnit.convert((this.start + this.delay) - System.currentTimeMillis(),TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o)
    {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    @Override
    public String toString()
    {
        return this.name+" ,mission is over,cost time: "+this.delay+" milliseconds";

    }
}